/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GenerarFactura.java
 *
 * Created on Jan 16, 2012, 8:46:16 PM
 */

package FACTURAS;

import CONTROLES.ControlCuenta;
import CONTROLES.ControlTipoCambio;
import INTERFAZ.Bienvenida;
import MODELOS.Cliente;
import MODELOS.Cuenta;
import MODELOS.Pago;
import MODELOS.TipoCambio;
import Reportes.Reporte;
import UTILITARIOS.Fecha;
import UTILITARIOS.Herramienta;
import UTILITARIOS.MiModelo;
import UTILITARIOS.NumerosLetras;
import UTILITARIOS.StringToDate;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;


/**
 *
 * @author VICENTE
 */
public class GenerarFactura extends javax.swing.JDialog {

    private ArrayList<Pago> pagosDisponibles;
    private Fecha fechaActual;
    private TipoCambio tipoCambio;
    private double total;
    private String detalle;
    private Cuenta cuenta;

    private Factura factura;
    private Dosificacion dosificacion;    
    private MiModelo modelo_pagos;
    

    /** Creates new form GenerarFactura */
    public GenerarFactura(javax.swing.JDialog parent, boolean modal, ArrayList<Pago> listPagos) {
        super(parent, modal);
        pagosDisponibles = listPagos;
        initComponents();
        iniciarValores();
        addEventos();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel12 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jLabel15 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        jLabel19 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaPagos = new javax.swing.JTable();
        jLabel21 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jLabel18 = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        jLabel23 = new javax.swing.JLabel();
        jLabel24 = new javax.swing.JLabel();
        jLabel26 = new javax.swing.JLabel();
        imprimirFactura = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel12.setFont(new java.awt.Font("Imprint MT Shadow", 0, 48));
        jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel12.setText("FACTURA");
        jLabel12.setName("jLabel12"); // NOI18N

        jPanel3.setName("jPanel3"); // NOI18N

        jLabel15.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel15.setText("Trinidad,");
        jLabel15.setName("jLabel15"); // NOI18N

        jLabel16.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel16.setText("jLabel16");
        jLabel16.setName("jLabel16"); // NOI18N

        jLabel17.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel17.setText("CLIENTE:");
        jLabel17.setName("jLabel17"); // NOI18N

        jLabel19.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel19.setText("NIT/CI:");
        jLabel19.setName("jLabel19"); // NOI18N

        jTextField1.setName("jTextField1"); // NOI18N

        jTextField2.setName("jTextField2"); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jLabel17, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel15, javax.swing.GroupLayout.Alignment.LEADING))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 341, Short.MAX_VALUE)
                    .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 341, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 79, Short.MAX_VALUE)
                .addComponent(jLabel19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(jLabel16))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel17)
                    .addComponent(jLabel19)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tablaPagos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaPagos.setName("tablaPagos"); // NOI18N
        jScrollPane1.setViewportView(tablaPagos);

        jLabel21.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel21.setText("DETALLE");
        jLabel21.setName("jLabel21"); // NOI18N

        jPanel4.setName("jPanel4"); // NOI18N

        jLabel18.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel18.setText("jLabel18");
        jLabel18.setName("jLabel18"); // NOI18N

        jLabel20.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel20.setText("Total Bs:");
        jLabel20.setName("jLabel20"); // NOI18N

        jLabel23.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel23.setText("Son:");
        jLabel23.setName("jLabel23"); // NOI18N

        jLabel24.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        jLabel24.setText("jLabel24");
        jLabel24.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jLabel24.setName("jLabel24"); // NOI18N

        jLabel26.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel26.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel26.setText("Bolivianos");
        jLabel26.setName("jLabel26"); // NOI18N

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel23)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, 555, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel26, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel18)
                    .addComponent(jLabel20))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel26)
                    .addComponent(jLabel23)
                    .addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        imprimirFactura.setText("Imprimir Factura");
        imprimirFactura.setName("imprimirFactura"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(239, 239, 239)
                        .addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE)
                        .addGap(229, 229, 229))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel21, javax.swing.GroupLayout.DEFAULT_SIZE, 813, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 813, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(imprimirFactura)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel12)
                .addGap(32, 32, 32)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel21)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(imprimirFactura)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void iniciarValores(){

        fechaActual = new Fecha();
        tipoCambio = new ControlTipoCambio().dameCambio();
        detalle = "";
        total = 0;
        factura = new Factura();
        cuenta = new Cuenta();

        jLabel16.setText(fechaActual.getFechaPrincipal());

        modelo_pagos = new MiModelo(new Object [][] {},new String [] {"Concepto", "Monto Bs"}, -1);
        double subtotal = 0.0;
        int numPagos = pagosDisponibles.size();
        if(numPagos >0){
            cuenta = new ControlCuenta().getCuenta(pagosDisponibles.get(0).getIdCuenta());
            Cliente c = cuenta.getCliente();
            jTextField1.setText(c.getNombreCompletoCliente());
            jTextField2.setText(String.valueOf(c.getNit()));
            for(int i=0;i<numPagos;i++){
                subtotal = pagosDisponibles.get(i).getMonto()*tipoCambio.getTipoCompra();
                detalle = detalle+pagosDisponibles.get(i).getNumeroPago()+"º Pago ";
                if(i+1<numPagos) detalle = detalle+" y ";
                total = total + subtotal;
            }
            detalle = detalle+ " de intereses por Inversion con la Empresa";
            Object [] auxPago = {
                    detalle,
                    Herramienta.redondearDoubleString(total)
                };
            modelo_pagos.addRow(auxPago);
        }
        
        total = Herramienta.redondear(total, 2);
      
        tablaPagos.setModel(modelo_pagos);

        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
        tcr.setHorizontalAlignment(SwingConstants.RIGHT);

        DefaultTableCellRenderer tcrc = new DefaultTableCellRenderer();
        tcrc.setHorizontalAlignment(SwingConstants.CENTER);

        tablaPagos.getColumnModel().getColumn(0).setCellRenderer(tcrc);
        tablaPagos.getColumnModel().getColumn(1).setCellRenderer(tcr);
        tablaPagos.getColumnModel().getColumn(1).setMaxWidth(200);

        jLabel18.setText(Herramienta.redondearDoubleString(total));
        StringTokenizer i = new StringTokenizer(String.valueOf(total),".");
        int bolivianos = Integer.parseInt(i.nextToken());
        int centavos = Integer.parseInt(i.nextToken());

        jLabel24.setText(new NumerosLetras().NumerosALetras(bolivianos)+" "+centavos+"/100");

    }

    private void addEventos(){
        imprimirFactura.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {                
                Calendar fecha_p = Calendar.getInstance();
                fecha_p.setTime(fechaActual.getFechaDate());
                fecha_p.add(Calendar.DATE, 14);
                dosificacion = new ControlDosificacion().DosificacionActiva(Bienvenida.sucursal.getIdSucursal());
                if(dosificacion == null){
                    JOptionPane.showMessageDialog(null, "No Existe una dosificacion de Facturas activa para la SUCURSAL "+Bienvenida.sucursal.getNombreSuc()+" Por lo que el sistema no puede emitir Facturas. \n Contacte al administrador del sistema para solucionar el problema. \n Verifique el pago De los intereses Haya sido Registrado e imprima el recibo. Gracias.", "Confirmación", JOptionPane.WARNING_MESSAGE);
                    dispose();
                }else{
                    if(fecha_p.getTime().getTime()>= dosificacion.getFechaLimite().getTime())
                        JOptionPane.showMessageDialog(null, "La fecha limite de emision de facturas se vencerá el "+new StringToDate().dateAstring(dosificacion.getFechaLimite())+"  Tome sus precauciones. Gracias", "Confirmación", JOptionPane.WARNING_MESSAGE);
                    
                    int res = 0;
                    String nombre = "----";
                    String nit = "0";
                    if(jTextField1.getText().compareTo("")==0)
                        res = 1;
                    else
                       nombre = jTextField1.getText();
                    if(jTextField2.getText().compareTo("")==0)
                       res = 1;
                    else
                        nit = jTextField2.getText();
                    if(res ==1)
                        res = JOptionPane.showConfirmDialog(null, "El NOMBRE del cliente o el CI/NIT estan en blanco desea imprimir la factura de todos modos?", "Advertencia", JOptionPane.OK_CANCEL_OPTION);
                    if(res ==0){
                        factura.setCliente(nombre);
                        factura.setNitCliente(nit);
                        factura.setFecha(fechaActual.getFechaDate());
                        factura.setIdDosificacion(dosificacion.getIdDosificacion());
                        factura.setDetalle(detalle);

                        factura.setMonto(total);
                        factura.setIdSucursal(Bienvenida.sucursal.getIdSucursal());
                        factura.setEstado("V");
                        factura.setContabilizada(false);
                        Factura fac = new ControlFactura().registrarFactura(factura);
                        if(fac != null){
                            dispose();
                            Reporte r = new Reporte();
                            r.ejecutarFactura(fac);
                        }else{
                            JOptionPane.showConfirmDialog(null, "ERROR No se Registro la Factura. informe del error al soporte tecnico del sistema", "Advertencia", JOptionPane.ERROR_MESSAGE);
                            System.out.println("no guardo paso algo en la bd");
                        }

                    }
                }
            }
        });
    }    
    public Factura getFactura() {
        return factura;
    }

    public void setFactura(Factura factura) {
        this.factura = factura;
    }


    /**
    * @param args the command line arguments
    */
    


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton imprimirFactura;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel26;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTable tablaPagos;
    // End of variables declaration//GEN-END:variables



}
